package com.gitee.qdbp.jdbc.support;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.gitee.qdbp.jdbc.plugins.DbPluginContainer;

/**
 * QdbcBoot的Spring初始化处理类<br>
 * 从ApplicationContext中扫描并注册所有的WhereSqlBuilder/UpdateSqlBuilder子类
 *
 * @author zhaohuihua
 * @version 20201124
 * @since 3.2.10
 */
public class QdbcBootSpringInitializer implements InitializingBean, ApplicationContextAware {

    private ApplicationContext context;
    /** 数据库插件容器类 **/
    private DbPluginContainer pluginContainer;

    @Override
    public void afterPropertiesSet() {
        if (pluginContainer == null) {
            pluginContainer = new DbPluginContainer();
        }
        if (context != null) {
            this.scanAndRegisterPlugin(pluginContainer, context);
        }
        this.customizePlugins(pluginContainer);
        DbPluginContainer.init(pluginContainer);
    }

    protected void scanAndRegisterPlugin(DbPluginContainer pluginContainer, ApplicationContext context) {
        PluginInstanceScanTools.scanAndRegisterWhereSqlBuilder(pluginContainer, context);
        PluginInstanceScanTools.scanAndRegisterUpdateSqlBuilder(pluginContainer, context);
        PluginInstanceScanTools.scanAndRegisterOrderBySqlBuilder(pluginContainer, context);
        PluginInstanceScanTools.scanAndRegisterBatchInsertExecutor(pluginContainer, context);
        PluginInstanceScanTools.scanAndRegisterBatchUpdateExecutor(pluginContainer, context);
    }

    protected void customizePlugins(DbPluginContainer pluginContainer) {
    }

    @Override
    public void setApplicationContext(ApplicationContext context) {
        this.context = context;
    }

    public ApplicationContext getApplicationContext() {
        return context;
    }

    /** 数据库插件容器类 **/
    public DbPluginContainer getPluginContainer() {
        return pluginContainer;
    }

    /** 数据库插件容器类 **/
    public void setPluginContainer(DbPluginContainer pluginContainer) {
        this.pluginContainer = pluginContainer;
    }

}
